/*
 * Copyright (c) 2015-2020, www.dibo.ltd (service@dibo.ltd).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.icesoft.system.permission.aspect;

import com.icesoft.framework.core.config.Cons;
import com.icesoft.framework.core.exception.BusinessException;
import com.icesoft.framework.core.util.AnnotationUtils;
import com.icesoft.framework.core.util.V;
import com.icesoft.framework.core.vo.Status;
import com.icesoft.system.auth.AuthProperties;
import com.icesoft.system.entity.BaseLoginUser;
import com.icesoft.system.permission.annotation.BindPermission;
import com.icesoft.system.permission.cache.PermissionCacheManager;
import com.icesoft.system.permission.entity.ApiPermission;
import com.icesoft.system.permission.exception.PermissionException;
import com.icesoft.system.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * BindPermission注解的切面处理
 *
 * @author mazc@dibo.ltd
 * @version v2.0
 * @date 2019/12/30
 */
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class BindPermissionAspect {

	private final AuthProperties authProperties;

	/**
	 * 注解切面
	 */
	@Pointcut("@annotation(com.icesoft.system.permission.annotation.BindPermission)")
	public void pointCut() {
	}

	/**
	 * 权限处理
	 *
	 * @param joinPoint
	 */
	@Before("pointCut()")
	public void before(JoinPoint joinPoint) {
		if (!authProperties.isEnablePermissionCheck()) {
			log.debug("BindPermission权限检查已停用，如需启用请删除配置项: icesoft.auth.enable-permission-check=false");
			return;
		}

		// 需要验证
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		BindPermission methodAnno = AnnotationUtils.getAnnotation(method, BindPermission.class);

		if (methodAnno != null && !methodAnno.develop()) {
			// 超级管理员 权限放过
			BaseLoginUser currentUser = SecurityUtils.getCurrentUser();
			if (SecurityUtils.getSubject().hasRole(Cons.ROLE_SUPER_ADMIN)) {
				return;
			}

			if (currentUser != null && currentUser.getId() == 1L) {
				return;
			}

			if(Objects.requireNonNull(SecurityUtils.getLoginUser()).getPermissions() == null || SecurityUtils.getLoginUser().getPermissions().isEmpty()){
				return;
			}

			String permissionCode = methodAnno.code();
			Class<?> controllerClass = joinPoint.getTarget().getClass();
			ApiPermission classAnno = PermissionCacheManager.getPermissionCodeWrapper(controllerClass);
			if (classAnno != null && V.notEmpty(classAnno.getCode())) {
				permissionCode = classAnno.getCode() + ":" + permissionCode;
			}

			try {
				SecurityUtils.getSubject().checkPermission(permissionCode);
			} catch (UnauthenticatedException e) {
				throw new BusinessException(Status.FAIL_INVALID_TOKEN, e);
			} catch (Exception e) {
				String loginUser = currentUser != null ? currentUser.getPhone() : null;
				log.warn("用户 {} 无 {} 的访问权限", loginUser, permissionCode);
				throw new PermissionException(Status.FAIL_NO_PERMISSION, e);
			}
		}

	}

}
